<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-02-22 10:43:19
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
    <div class="stationTable">
        <!-- <nu-col :span="24" style="height:calc(130px - 20px);">
                    <nutbTitle title="计量点表"></nutbTitle> -->
        <NuVerifyForm :model="formData" ref="formData" label-width="100px" class="searchForm" @searchForm="searchForm"
            :buttons="fyButtons">
            <NuformItem label="计量点名称" prop="name" width="auto">
                <nu-input type="text" v-model="formData.name" size="middle" placeholder="请输入计量点名称"></nu-input>
            </NuformItem>

            <div class="btnBox">
                <nu-button type="primary" class="searchButton" @click="searchTable">搜索</nu-button>
                <nu-button class="searchButton" @click="clearParams">清除</nu-button>
                <!-- <nu-button type="primary" class="searchButton" @click="importTable">导入</nu-button> -->
            </div>
        </NuVerifyForm>
        <div class="line"></div>
        <div style="height:35px;position: relative;padding: 0 10px;" class="renovateTime">
            <nu-button class="searchButton" @click="addTable">新增</nu-button>
        </div>
        <!-- </nu-col> -->
        <!-- <nu-col :span="24" style="height: calc(100% - 130px - 20px);">
            <nutbTitle title="计量点列表"></nutbTitle> -->
        <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
            :operates="operates(this)" border :pagination="pagination" @handleSizeChange="handleSizeChange"
            @handleChangePage="handleChangePage" @cell-mouse-enter="cellMouseClick">
        </NuTableList>
        <!-- </nu-col> -->
        <nu-dialog :title="dialogTitle" :visible.sync="dialogShow" width="42%" center :close-on-click-modal="false"
            top="5vh" :modal-append-to-body="false" @close="diaClose">
            <div class="dialogHeaderSearch">
                <NuVerifyForm :model="dialogFormData" ref="dialogFormData" label-width="120px" class="submitForm"
                    @submitForm="diaSubmitForm" :buttons="fyButtons">
                    <NuformItem label="计量点名称" prop="name" width="46%" :rules="[{ required: true, message: '计量点名称不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.name" size="middle" :disabled="dialogFormDisabled"
                            placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="电能表厂家型号" prop="meterMode" width="46%"
                        :rules="[{ required: true, message: '电能表厂家型号不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.meterMode" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <!-- <NuformItem label="表计地址" prop="meterAddress" width="46%"
                        :rules="[{ required: true, message: '表计地址不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.meterAddress" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem> -->
                    <NuformItem label="CT变比" prop="ctChange" width="46%" :rules="[{ required: true, message: 'CT变比不能为空' }]">
                        <nu-input type="Number" v-model="dialogFormData.ctChange" size="middle"
                            :disabled="dialogFormDisabled"
                            @input="(value) => { if (value.indexOf('.') > 0) { dialogFormData.ctChange = value.slice(0, value.indexOf('.') + 4) } }"
                            placeholder="请输入" @blur="coefBlur($event, 3)"></nu-input>
                    </NuformItem>
                    <NuformItem label="PT变比" prop="ptChange" width="46%" :rules="[{ required: true, message: 'PT变比不能为空' }]">
                        <nu-input type="Number" v-model="dialogFormData.ptChange" size="middle"
                            :disabled="dialogFormDisabled"
                            @input="(value) => { if (value.indexOf('.') > 0) { dialogFormData.ptChange = value.slice(0, value.indexOf('.') + 4) } }"
                            placeholder="请输入" @blur="coefBlur($event, 3)"></nu-input>
                    </NuformItem>
                    <NuformItem label="电表小数位" prop="meterDot" width="46%"
                        :rules="[{ required: true, message: '电表小数位不能为空' }]">
                        <nu-select class="searchSelect" :filterable="true" :list="meterList" type="text"
                            v-model="dialogFormData.meterDot" autocomplete="off"
                            style="width: calc(100% - 5px);margin-left: 2px;" :disabled="dialogFormDisabled"
                            placeholder="请选择">
                        </nu-select>
                    </NuformItem>
                    <NuformItem label="规约类型" prop="protocolType" width="46%"
                        :rules="[{ required: true, message: '规约类型不能为空' }]">
                        <nu-select class="searchSelect" :filterable="true" :list="agreList" type="text"
                            v-model="dialogFormData.protocolType" autocomplete="off"
                            style="width: calc(100% - 5px);margin-left: 2px;" :disabled="dialogFormDisabled"
                            placeholder="请输入">
                        </nu-select>
                    </NuformItem>
                    <!-- <NuformItem label="端口号" prop="port" width="46%" :rules="[{ required: true, message: '端口号不能为空' }]">
                        <nu-input type="Number" v-model="dialogFormData.port" size="middle" :disabled="dialogFormDisabled"
                            placeholder="请输入"></nu-input>
                    </NuformItem> -->
                    <NuformItem label="链路地址" prop="linkAddress" width="46%"
                        :rules="[{ required: true, message: '链路地址不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.linkAddress" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                </NuVerifyForm>
                <nu-button class="dialogSearchButton" type="primary" @click="diaClose">取消</nu-button>
                <nu-button class="dialogSearchButton" type="primary" @click="diaSave"
                    v-if="dialogTitle == '编辑'">确定</nu-button>
                <nu-button class="dialogSearchButton" type="primary" @click="diaSave"
                    v-if="dialogTitle == '新增'">确定</nu-button>

            </div>
        </nu-dialog>
        <nu-dialog :title="upload.title" :visible.sync="upload.open" width="30%" center :close-on-click-modal="false"
            top="5vh" :modal-append-to-body="false">
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :auto-upload="false" drag :data="upload.data" name="file">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                                                                                                                                        @click="importTemplate">下载模板</el-link> -->
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </nu-dialog>
    </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue"
import nutbTitle from "@/components/base/tableTitle.vue"
import NuVerifyForm from "@/components/verify-form"
import NuformItem from "@/components/verify-form/form-item.vue"
import nuInput from "@/components/base/input"
import nuSelect from "@/components/base/select"
import nuButton from "@/components/base/button"
import NuTableList from "@/components/tableList/TableFormList"
import nuDialog from "@/components/base/dialog"
import { getDateTime } from '@/utils/ruoyi'
const operates = that => [
    {
        label: '编辑',
        icon: '',
        width: '50px',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.openEdit(row);
        },
    },
    // {
    //   isShow: row => {
    //     return false;
    //   },
    // },
    {
        label: '',
        icon: '',
        width: '50px',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            // that.openDetail(row);
        },
        render: (h, params) => {
            return h('nu-button', {
                props: {
                    type: 'text'
                },
                class: 'tableOperateBtn',
                on: {
                    click: () => {
                        that.forbidden(params.row);
                    },

                }
            }, params.row.status == 0 ? '禁用' : '重新启用');
        },
    },
    {
        label: '删除',
        icon: '',
        width: '50px',
        isShow: row => {
            return row.status == 1 ? true : false;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.tbRowdetele(row);
        },
    },
];
import { getToken } from "@/utils/auth";
export default {
    name: "stationTable",
    components: { nuCol, nutbTitle, NuVerifyForm, NuformItem, nuInput, nuSelect, nuButton, NuTableList, nuDialog },
    data() {
        return {
            formData: {
                name: ''
            },
            dialogFormData: {
                name: '',
                meterMode: '',
                meterAddress: '',
                ctChange: '',
                ptChange: '',
                meterDot: '',
                protocolType: '',
                port: '',
                linkAddress: ''

            },
            fyButtons: [],
            operates,
            pagination: {
                pageSize: 20,
                total: 0,
                pageNum: 1,
            },
            dialogTitle: '',
            dialogShow: false,
            meterList: [{ label: '1', value: 1 }, { label: '2', value: 2 }, { label: '3', value: 3 }, { label: '4', value: 4 }],
            agreList: [{ label: '102类型', value: 1 }],
            measureTypeList: [],
            columns: [
                {
                    label: '序号',
                    prop: 'ranking',
                    width: '70px',
                    render: (h, params) => {
                        return h('span', params.index + 1 + (this.pagination.pageNum - 1) * this.pagination.pageSize);
                    },
                },
                {
                    label: '计量点名称',
                    prop: 'name',
                },
                {
                    label: '电能表厂家型号',
                    prop: 'meterMode',
                    width: '150px',
                },
                // {
                //     label: '表计地址',
                //     prop: 'meterAddress',
                // },
                {
                    label: 'CT变比',
                    prop: 'ctChange',
                },
                {
                    label: 'PT变比',
                    prop: 'ptChange',
                },
                {
                    label: '电表小数位',
                    prop: 'meterDot',
                },
                {
                    label: '规约类型',
                    prop: 'protocolType',
                    render: (h, params) => {
                        if (params.row.protocolType || params.row.protocolType == 0) {
                            let span = '';
                            this.agreList.forEach(item => {
                                if (item.value == params.row.protocolType) {
                                    span = item.label;
                                }
                            });
                            return h('span', span);
                        }
                    },
                },
                // {
                //     label: '端口号',
                //     prop: 'port',
                // },
                {
                    label: '链路地址',
                    prop: 'linkAddress',
                },
                {
                    label: '状态',
                    prop: 'status',
                    render: (h, params) => {
                        return h('span', params.row.status == 0 ? '正常' : '禁用',);
                    },
                }
            ],
            dataSource: [{}],
            options: {
                'default-expand-all': true,
                'element-loading-background': 'rgba(225,239,242)',
                'element-loading-text': '数据正在加载中',
                'row-key': 'pid',
                'header-cell-style': {
                    background: 'rgba(105, 159, 209, 0.7)',
                    color: '#fff',
                    fontWeight: 'bold',
                    fontsize: '16px',
                },
                height: 'calc(100vh - 310px)',
                props: {
                    // fixed: 'right'
                }
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + window.api.importData,
                // 上传时附带的额外参数
                data: { id: 1 }
            },
            tableActiveRow: {}
        };
    },
    computed: {
        dialogFormDisabled() {
            return this.dialogTitle == '详情'
        }
    },
    created() {
    },
    mounted() {
        this.getMeteringPointData();
    },
    methods: {
        /**
         * 查询
         */
        searchTable() {
            this.$refs['formData'].searchForm('form');
        },
        /**
         * form组件内置查询事件
         */
        searchForm(val) {
            if (val) {
                this.getMeteringPointData();
            }
        },
        /**
         * 新增
         */
        addTable() {
            this.dialogTitle = '新增'
            this.dialogShow = true
        },
        /**
         * 导入
         */
        importTable() {
            this.upload.title = "厂站表导入";
            this.upload.open = true;
        },
        /**
         * 清除数据
         */
        clearParams() {
            this.resetForm('formData')
        },
        /**
         * 重置表单
         */
        resetForm(formName) {
            this.$refs[formName].resetForm('form');
            for (let k in this[formName]) {
                if (Object.prototype.toString.call(this[formName][k]) == "[object String]") {
                    this[formName][k] = ''
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Array]") {
                    this[formName][k] = []
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Number]") {
                    this[formName][k] = ''
                }
            }
        },
        /**
         * 系数验证小数点4位，不足补齐0
         * @param {*} e 
         * @param {*} n 
         */
        coefBlur(e, n) {
            n = n ? parseInt(n) : 0;
            if (n <= 0) {
                return Math.round(e.target.value);
            }
            e.target.value = Math.round(e.target.value * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
            e.target.value = Number(e.target.value).toFixed(n); //补足位数
        },
        cellMouseClick(row, column, cell, event) {
            this.tableActiveRow = row
        },
        /**
         * 表格-禁用
         */
        forbidden(row) {
            row = this.tableActiveRow
            // 禁用状态下调用重启
            if (row.status == 1) {
                this.$confirm('是否重新启用该计量点?', '确认重启', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.forbiddenMeteringPointTableData(row)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重启'
                    });
                });
                // 
            } else if (row.status == 0) {
                this.$confirm('是否禁用该计量点，禁用后该计量点下数据将被系统过滤?', '确认禁用', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.forbiddenMeteringPointTableData(row)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消禁用'
                    });
                });
            }

        },
        /**
         * 每页条数变化事件
         */
        handleSizeChange(val) {
            this.pagination.pageNum = 1;
            this.pagination.pageSize = val;
            this.getMeteringPointData();
        },
        /**
         * 改变分页触发事件
         */
        handleChangePage(val) {
            this.pagination.pageNum = val;
            this.getMeteringPointData();
        },
        /**
         * 表格-编辑
         */
        openEdit(row) {
            this.dialogTitle = '编辑'
            this.dialogShow = true
            Object.assign(this.dialogFormData, row)
        },
        /**
         * 表格-详情
         */
        openDetail(row) {
            this.dialogTitle = '详情'
            this.dialogShow = true
            Object.assign(this.dialogFormData, row)
        },
        /**
         * 表格-删除
         */
        tbRowdetele(row) {
            this.$confirm('确定要删除计量点【' + row.name + '】吗？', '确认删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delMeteringPointTableData(row)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        /**
         * dialogFormData组件内置提交事件
         */
        diaSubmitForm(val) {
            if (val) {
                if (this.dialogTitle == '编辑') {
                    this.editMeteringPointTableData()
                } else if (this.dialogTitle == '新增') {
                    this.addMeteringPointTableData()
                }
            }
        },
        /**
         * 弹窗-保存
         */
        diaSave() {
            this.$refs['dialogFormData'].submitForm('form');
        },
        /**
         * 弹窗-关闭
         */
        diaClose() {
            this.dialogShow = false
            this.resetForm('dialogFormData')
        },
        /**
         * 获取表格数据
         */
        getMeteringPointData() {
            let postData = {
                ...this.formData,
                ...this.pagination,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpGet(window.api.getMeteringPointData, postData).then(res => {
                if (res.code == 200) {
                    this.pagination.total = res.total;
                    this.dataSource = res.rows;
                    this.diaClose()
                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 编辑接口
         */
        editMeteringPointTableData() {
            let postData = {
                ...this.dialogFormData,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.addMeteringPointData, postData).then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: '成功',
                        type: 'success'
                    })
                    this.getMeteringPointData()
                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 删除表格数据
         */
        delMeteringPointTableData(row) {
            let postData = {
                ids: [row.id]
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.delMeteringPointData, postData).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getMeteringPointData()
                } else {
                    this.$message({
                        type: 'info',
                        message: res.msg
                    });
                }
            }).catch(err => {

            });
        },
        /**
         * 新增接口
         */
        addMeteringPointTableData() {
            let postData = {
                ...this.dialogFormData,
                // updateDate: getDateTime('time'),
                status: 0
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.addMeteringPointData, postData).then(res => {
                if (res.code == 200 && res.data) {
                    this.$message({
                        message: '成功',
                        type: 'success'
                    })
                    this.getMeteringPointData()
                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 禁用接口
         */
        forbiddenMeteringPointTableData(row) {
            console.log(row)
            let postData = {
                id: row.id,
                status: row.status == 0 ? 1 : 0,
                updateBy: row.updateBy
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpGet(window.api.forbiddenMeteringPointTableData, postData).then(res => {
                if (res.code == 200 && res.data) {
                    this.$message({
                        message: '成功',
                        type: 'success'
                    })
                    this.getMeteringPointData()
                } else {
                }
            }).catch(err => {

            });
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$message({
                message: response.message,
                type: 'success'
            })
            this.searchTable();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        }
    }
};
</script>
    
<style scoped lang="scss">
.stationTable {
    height: 100%;
}

.searchForm {
    // height: calc(100% - 40px);
    display: flex;
    // align-items: center;
    position: relative;
    flex-wrap: wrap;
    padding-right: 160px;
}

.submitForm {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.btnBox {
    display: flex;
    float: right;
    z-index: 10;
    position: absolute;
    // top: 15px;
    right: 10px;
    margin: 10px 0 0 0;
}

.dialogHeaderSearch {
    background-color: var(--model-bgc);
    padding: 10px;
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    justify-content: right;
}

::v-deep .el-upload {
    width: 100%;

    .el-upload-dragger {
        width: auto;
    }
}
</style>
    
    